<template>
    <div class="dialog_content">
        <el-form :model="ruleForm" ref="ruleForm" label-width="120px" class="demo-ruleForm" label-position="left"
            :rules="rules">
            <el-row>
                <el-col :span="11">
                    <el-form-item label="添加分组名称" prop="groupTool" class="group_item">
                        <el-input placeholder="请输入内容" v-model.trim="ruleForm.groupTool" class="input-with-select">
                            <el-button slot="append" icon="el-icon-plus"
                                :disabled="isDisabled || !Boolean(ruleForm.groupTool)" @click="addGroup"></el-button>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="2">
                    <el-popover placement="right" width="350" trigger="hover">
                        <div class="popover_content">
                            <div>·必须以字母开头，支持字母，数字，中、下划线；</div>
                            <div>·不能包含空格特殊字符；</div>
                            <div>·最后一个字符不能为下划线或中划线；</div>
                            <div>·长度为1-8个字符；</div>
                        </div>
                        <i class="el-icon-warning-outline" slot="reference"
                            style="line-height: 40px;margin-left: 15px;"></i>
                    </el-popover>
                </el-col>
                <el-col :span="11">

                </el-col>
            </el-row>

            <el-row>
                <el-col :span="11">
                    <span class="span_item">
                        <span style="font-weight: 700;">分组池</span>
                    </span>
                </el-col>

                <el-col :span="11">
                    <el-form-item label="样品池" prop="name" style="padding-left: 65px;">
                        <el-input v-model="ruleForm.sample" @input="searchItem">
                            <i slot="prefix" class="el-input__icon el-icon-search"></i>
                        </el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="2">
                    <div class="all_select" style="line-height: 40px;margin-left: 10px; cursor: pointer !important;"
                        @click="allAddItem">
                        <i class="el-icon-success themeTopToolColor"></i>
                        <span>全选</span>
                    </div>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="4">
                    <div class="group_left">
                        <div v-for="(item, index) in groupList" :key="index" class="group_left_item"
                            :class="{ is_active: itemShow === index }" @click="itemShow = index"
                            @mouseover="editIsShow = index" @mouseleave="editIsShow = null">
                            <el-checkbox v-model="item.ischecked" @change="changeItemStatus($event, index)"></el-checkbox>
                            <span class="group_left_item_content">{{ item.title }}</span>
                            <el-popover placement="right" width="150" trigger="click" ref="popoverDom">
                                <div>
                                    <el-input size="small" v-model="groupItemName"></el-input>
                                </div>
                                <div style="margin-top: 10px;">
                                    <el-button type="primary" size="mini" class="themeTopToolbgColor"
                                        @click="verify(index)">确定</el-button>
                                    <el-button size="mini" @click="cancel">取消</el-button>
                                </div>
                                <el-tooltip class="item" effect="dark" content="重命名" placement="top" slot="reference"
                                    style="margin-right: 12px;">
                                    <i class="el-icon-edit group_left_item_edit" v-show="editIsShow === index"
                                        @click="editGroupItem(index)"></i>
                                </el-tooltip>
                            </el-popover>

                        </div>
                    </div>
                </el-col>
                <el-col :span="9">
                    <div class="group_middle">
                        <template v-if="groupList.length && groupList[itemShow]">
                            <div v-for="(item, index) in groupList[itemShow].content" :key="index" class="group_middle_item"
                                @mouseover="deleteShow = index" @mouseleave="deleteShow = null">
                                <el-tooltip placement="top">
                                    <div slot="content">{{ item }}</div>
                                    <span>{{ item }}</span>
                                </el-tooltip>
                                <i class="el-icon-delete" v-show="deleteShow == index" @click="deleteItem(item, index)"></i>
                            </div>
                        </template>
                    </div>
                </el-col>
                <el-col :span="11">
                    <div class="group_right">
                        <template v-for="(item, index) in sampleList">
                            <el-tooltip placement="top">
                                <div slot="content">{{ item }}</div>
                                <div class="group_right_item" @click="addItem(item, index)">{{ item }}</div>
                            </el-tooltip>
                        </template>
                    </div>
                </el-col>
            </el-row>
            <div class="group_btn">
                <div class="group_btn_left">
                    <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="changeStatus"></el-checkbox>
                    <el-button icon="el-icon-delete" size="mini" :disabled="!checkAll && !isIndeterminate"
                        @click="delItem">删除</el-button>
                    <el-popover placement="right" width="400" trigger="click">
                        <el-input type="textarea" :rows="12" placeholder="请输入内容" v-model="textareaList">
                        </el-input>
                        <el-button size="mini" type="primary" style="float:right;margin-top:5px"
                            @click="customGroup">确定</el-button>
                        <el-button icon="el-icon-edit" size="mini" slot="reference">批量修改</el-button>
                    </el-popover>

                    <el-button icon="el-icon-refresh-left" size="mini" @click="cancelList">撤销修改</el-button>
                </div>
                <div class="group_btn_right">
                    <el-button type="primary" size="mini" class="themeTopToolbgColor" @click="verifyDialog">确认</el-button>
                    <el-button size="mini" @click="cancelDialog">取消</el-button>
                </div>
            </div>
        </el-form>
    </div>
</template>

<script>
import { deepClone } from '@/utils';
import { compareGroupRequest } from '@/api/tools'
export default {
    name: 'GenecloudUiDialogCom',
    props: {
        groupObject: {
            type: Object,
            default: () => { }
        }
    },
    data() {
        let validate2 = (rule, value, callback) => {
            const index = this.groupList.findIndex(item => item.title == this.ruleForm.groupTool)
            if (index !== -1) {
                this.isDisabled = true
                callback(new Error("分组名已存在"));
            } else if (!/^[a-zA-Z]+([a-zA-Z_0-9]+)?$/.test(value)) {
                this.isDisabled = true
                callback(new Error("格式错误！"));
            } else if (value.length > 8 || value.length < 1) {
                this.isDisabled = true
                callback(new Error("格式错误！"));
            } else {
                this.isDisabled = false
                callback();
            }
        }
        return {
            ruleForm: {
                groupTool: '',
                option: '',
                sample: ''
            },
            //重命名标签
            editIsShow: null,
            //选中的menu
            itemShow: 0,
            //全选
            isIndeterminate: false,
            checkAll: '',
            //样品池
            result: [],
            sampleList: [],
            //分组池
            isDisabled: true,
            groupList: [],
            deleteShow: null,
            groupItemName: '',
            rules: {
                groupTool: [
                    { required: true, validator: validate2, trigger: ['change'] },
                ]
            },
            cancelObject: JSON.parse(localStorage.getItem('cancelObject')),
            textareaList: ''
        };
    },
    watch: {
        groupObject: {
            handler(val, newVal) {
                this.init(val)
            },
            immediate: true,
            deep: true
        },
    },
    mounted() {

    },

    methods: {
        init({ dataGroupList, sampleList }) {
            if (Boolean(dataGroupList.length)) {
                this.groupList = dataGroupList.reduce((pre, item, index) => {
                    pre.push({
                        title: item.groupTitle,
                        ischecked: false,
                        content: item.content.map(i => i.title)
                    })
                    return pre
                }, [])
                this.sampleList = deepClone(sampleList)
                this.result = dataGroupList.reduce((pre, item, index) => {
                    let arr = item.content.map(i => i.title)
                    pre.push(...arr)
                    return pre
                }, []).concat(this.sampleList)

            } else {
                this.groupList = []
                this.sampleList = deepClone(sampleList)
            }
        },
        //撤销修改
        cancelList() {
            this.init(this.cancelObject)
        },
        addGroup() {
            this.groupList.push(
                {
                    title: this.ruleForm.groupTool,
                    content: [],
                    ischecked: false
                }
            )
            this.ruleForm.groupTool = ''
        },
        addItem(item, index) {
            if (this.groupList.length > 0) {
                this.groupList[this.itemShow].content.push(item)
                this.sampleList.splice(index, 1)
            }
        },
        allAddItem() {
            if (this.groupList.length > 0) {
                // this.sampleList.forEach((item, index) => {
                this.groupList[this.itemShow].content.push(...this.sampleList)
                this.sampleList.splice(0, this.sampleList.length)
                // })
            }
        },
        //反选
        changeItemStatus(value, index) {
            this.groupList[index].ischecked = value
            const isAll = this.groupList.every(item => item.ischecked)
            this.checkAll = isAll
            this.isIndeterminate = isAll ? false : true
        },
        //全选功能
        changeStatus() {
            this.groupList.map(item => item.ischecked = this.checkAll)
            this.isIndeterminate = false;
        },
        //删除分组池内容
        delItem() {
            const item = this.groupList.reduce((pre, item, index) => {
                if (item.ischecked) {
                    pre.push(...item.content)
                }
                return pre
            }, [])
            this.sampleList.push(...item)
            this.groupList = this.groupList.filter(item => !item.ischecked)
            if (this.groupList.length <= 0) {
                this.checkAll = false
            }
        },
        //重命名
        editGroupItem(index) {
            this.groupItemName = this.groupList[index].title
            // console.log();
        },
        //确定
        verify(index) {
            const a = this.groupList.find(i => i.title === this.groupItemName)
            const b = this.groupList.findIndex(i => i.title === this.groupItemName)
            if (a && b !== index) return this.$message.error('分组名重复！')
            document.body.click()
            this.groupList[index].title = this.groupItemName
        },
        //取消
        cancel() {
            document.body.click()
        },
        //筛选
        searchItem() {
            let groupItems = []
            let filterList = []
            this.groupList.forEach(item => {
                groupItems = groupItems.concat(item.content)
            })
            filterList = this.result.reduce((pre, item, index) => {
                if (!groupItems.includes(item)) {
                    pre.push(item)
                }
                return pre
            }, [])
            if (!this.ruleForm.sample) {
                this.sampleList = filterList
            } else {
                this.sampleList = filterList.filter(item => item.includes(this.ruleForm.sample))
            }
        },
        //删除
        deleteItem(item, index) {
            this.sampleList.push(item)
            this.groupList[this.itemShow].content.splice(index, 1)
        },
        //确认分组条件
        verifyDialog() {
            let arr = this.groupList.reduce((pre, item, index) => {
                let content = item.content.map(i => {
                    return { ischecked: true, title: i }
                })
                pre.push({
                    ischecked: true,
                    groupTitle: item.title,
                    content
                })
                return pre
            }, [])
            if (arr.length < 1) return this.$message.error('至少需要存在一种分组！')
            this.$emit('changeGroupList', { dataGroupList: arr, sampleList: this.sampleList })
        },
        cancelDialog() {
            this.$emit('closeDialog', false);
        },
        //根据分组调整
        changeGroup(value) {
            const { groupItems, groupList } = value
            this.sampleList = groupList
            this.result = groupList
            this.groupList = groupItems
        },
        async customGroup() {
            //this.cancelObject 原始数据
            //this.textareaList 输入文本
            let pageCode = window.location.search.split('=')[1]
            const res = await compareGroupRequest({
                taskId: null,
                pageCode,
                text: this.textareaList
            })
            if (res.code !== 200) return this.$message.error(res.message)
            if (res.message) {
                this.$confirm(`${res.message},是否继续操作？`, '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                    beforeClose: async (action, instance, done) => {
                        if (action === 'confirm') {
                            this.init(res.data)
                            this.textareaList = ''
                        } else if (action === 'cancel') {
                            this.$message({
                                message: '取消操作',
                            })
                            this.textareaList = ''
                        }
                        done();
                    }
                }).catch(() => { })
            } else {
                this.init(res.data)
                this.textareaList = ''
                document.body.click()
            }
        }
    },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.themeTopToolbgColor {
    background-color: $themeTopToolColor;
    border: 0;
}

.themeTopToolColor {
    color: $themeTopToolColor;
}

.dialog_content {
    .span_item {
        line-height: 40px;
    }

    // .el-form-item{
    //     margin: 0;
    // } 

    .group_item {
        position: relative;

        ::v-deep .el-input__inner {
            border-radius: 6px 0 0 6px;

        }
    }

    .group_left,
    .group_right,
    .group_middle {
        height: 300px;
        border: 1px solid #ccc;
        overflow-y: auto;
    }

    .group_middle {
        border-left: 0;
    }


    .group_left {
        display: flex;
        flex-direction: column;
        padding: 15px 0;

        .group_left_item {

            cursor: pointer;
            display: flex;
            justify-content: space-around;
            width: 100%;
            padding: 6px 15px;

            &:hover {
                background-color: #eaf6ff;
            }

            .group_left_item_content {
                width: 100%;
                padding: 0 5px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            .popover_btn {
                padding-top: 10px;
            }

            &.is_active {
                color: $themeTopToolColor;
                background-color: #e9f6ff;
            }
        }
    }

    .group_middle {
        display: flex;
        flex-wrap: wrap;
        align-content: flex-start;
        padding: 15px;

        .group_middle_item {
            display: flex;
            align-items: center;
            text-align: center;
            cursor: pointer;
            width: 72px;
            height: 32px;
            line-height: 32px;
            margin: 0 10px 10px 0;
            background-color: #eae9e9;

            &:nth-child(3n) {
                margin-right: 0;
            }

            span {
                padding-right: 10px;
                width: 60px;
                overflow: hidden;
                text-overflow: ellipsis;
                text-wrap: nowrap;
            }

            &:hover {
                background-color: #eaf6ff;
                color: $themeTopToolColor;
            }

        }
    }

    .group_right {
        margin-left: 25px;
        display: flex;
        flex-wrap: wrap;
        align-content: flex-start;
        padding: 15px;

        .group_right_item {
            text-align: center;
            cursor: pointer;
            width: 75px;
            overflow: hidden;
            text-wrap: nowrap;
            text-overflow: ellipsis;
            height: 32px;
            line-height: 32px;
            margin: 0 10px 10px 0;
            background-color: #eae9e9;

            &:hover {
                background-color: #eaf6ff;
                color: $themeTopToolColor;
            }

            &:nth-child(3n) {
                margin-right: 0;
            }

        }
    }

    .group_btn {
        margin-top: 15px;
        display: flex;
        justify-content: space-between;
    }
}
</style>